const http = require('http')
const parse = require('url').parse
const join = require('path').join
const fs = require('fs')

const root = __dirname

const server = http.createServer(function(req,res){
    const url = parse(req.url)
    const path = join(root,url.pathname)

    fs.stat(path,function(err,stat){
        if(err){
            res.write(JSON.stringify(err))
            if('ENOENT' == err.code){
                res.statusCode = 404
                res.end('NOT Found')
            }else{
                res.statusCode = 500
                res.end('Internet Server Error')
            }
        }else{
            res.setHeader('Content-Length',stat.size)
            var stream = fs.createReadStream(path)
            stream.pipe(res)
            stream.on('error',function(err){
                res.statusCode = 500
                res.end('Internet Server Error')
            })
        }
        
    })

})
server.listen('3000')

console.log('server is running on 3000....')